package com.power.leopard.extension;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

public final class ExtensionLoader {

	private static Map<Class<?>, Object> extensions = new ConcurrentHashMap<Class<?>, Object>();

	public static <T> T getInstance(Class<T> clazz) {
		T object = (T) extensions.get(clazz);
		if (object == null) {
			object = newInstance(clazz);
			if (object != null) {
				extensions.put(clazz, object);
			}
		}
		return object;
	}

	public static <T> T newInstance(Class<T> clazz) {
		ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
		for (T service : serviceLoader) {
			return service;
		}
		return null;
	}

	public static <T> List<T> newInstanceList(Class<T> clazz) {
		List<T> services = new ArrayList<T>();
		ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
		for (T service : serviceLoader) {
			services.add(service);
		}
		return services;
	}

	public static <T> List<T> getExtensionList(Class<T> clazz) {
		List<T> object = (List<T>) extensions.get(clazz);
		if (object == null) {
			object = newInstanceList(clazz);
			if(object != null){
				extensions.put(clazz, object);
			}
		}
		return object;
	}
}
